// 后端服务检查工具
export class BackendChecker {
  constructor() {
    this.baseUrl = 'http://127.0.0.1:8891'
  }

  // 检查端口是否被占用
  async checkPort() {
    try {
      const response = await fetch(`${this.baseUrl}/health`, {
        method: 'GET',
        mode: 'no-cors',
        timeout: 3000
      })
      return {
        success: true,
        message: '端口8891可访问'
      }
    } catch (error) {
      return {
        success: false,
        message: '端口8891不可访问 - 可能服务未启动'
      }
    }
  }

  // 检查常见的API端点
  async checkApiEndpoints() {
    const endpoints = [
      '/api/health',
      '/health',
      '/status',
      '/api/status',
      '/',
      '/api/alerts',
      '/Alert/list'
    ]

    const results = []
    
    for (const endpoint of endpoints) {
      try {
        const response = await fetch(`${this.baseUrl}${endpoint}`, {
          method: 'GET',
          mode: 'no-cors',
          timeout: 3000
        })
        results.push({
          endpoint,
          success: true,
          message: '可访问'
        })
      } catch (error) {
        results.push({
          endpoint,
          success: false,
          message: '不可访问'
        })
      }
    }
    
    return results
  }

  // 检查WebSocket端点
  async checkWebSocketEndpoints() {
    const wsEndpoints = [
      '/ws/alerts',
      '/ws',
      '/websocket',
      '/socket.io',
      '/ws/water-quality'
    ]

    const results = []
    
    for (const endpoint of wsEndpoints) {
      const wsUrl = `${this.baseUrl.replace('http', 'ws')}${endpoint}`
      
      try {
        const ws = new WebSocket(wsUrl)
        
        const result = await new Promise((resolve) => {
          const timeout = setTimeout(() => {
            ws.close()
            resolve({
              endpoint,
              success: false,
              message: '连接超时'
            })
          }, 3000)

          ws.onopen = () => {
            clearTimeout(timeout)
            ws.close()
            resolve({
              endpoint,
              success: true,
              message: 'WebSocket连接成功'
            })
          }

          ws.onerror = () => {
            clearTimeout(timeout)
            resolve({
              endpoint,
              success: false,
              message: 'WebSocket连接失败'
            })
          }
        })
        
        results.push(result)
      } catch (error) {
        results.push({
          endpoint,
          success: false,
          message: `创建WebSocket失败: ${error.message}`
        })
      }
    }
    
    return results
  }

  // 运行完整检查
  async runFullCheck() {
    console.log('🔍 开始后端服务检查...')
    
    const results = {
      timestamp: new Date().toISOString(),
      baseUrl: this.baseUrl,
      portCheck: null,
      apiEndpoints: [],
      webSocketEndpoints: [],
      summary: {
        totalTests: 0,
        passed: 0,
        failed: 0
      }
    }

    // 检查端口
    console.log('📡 检查端口8891...')
    results.portCheck = await this.checkPort()
    results.summary.totalTests++
    if (results.portCheck.success) {
      results.summary.passed++
    } else {
      results.summary.failed++
    }

    // 检查API端点
    console.log('🔌 检查API端点...')
    results.apiEndpoints = await this.checkApiEndpoints()
    results.apiEndpoints.forEach(endpoint => {
      results.summary.totalTests++
      if (endpoint.success) {
        results.summary.passed++
      } else {
        results.summary.failed++
      }
    })

    // 检查WebSocket端点
    console.log('🔌 检查WebSocket端点...')
    results.webSocketEndpoints = await this.checkWebSocketEndpoints()
    results.webSocketEndpoints.forEach(endpoint => {
      results.summary.totalTests++
      if (endpoint.success) {
        results.summary.passed++
      } else {
        results.summary.failed++
      }
    })

    console.log('📊 检查完成:', results)
    return results
  }

  // 生成检查报告
  generateCheckReport(results) {
    const report = []
    
    report.push('🔍 后端服务检查报告')
    report.push('=' .repeat(50))
    report.push(`检查时间: ${new Date(results.timestamp).toLocaleString()}`)
    report.push(`目标地址: ${results.baseUrl}`)
    report.push('')
    
    report.push('📊 检查结果汇总:')
    report.push(`  总测试数: ${results.summary.totalTests}`)
    report.push(`  成功: ${results.summary.passed}`)
    report.push(`  失败: ${results.summary.failed}`)
    report.push('')
    
    report.push('📡 端口检查:')
    report.push(`  状态: ${results.portCheck.success ? '✅ 可访问' : '❌ 不可访问'}`)
    report.push(`  信息: ${results.portCheck.message}`)
    report.push('')
    
    report.push('🔌 API端点检查:')
    results.apiEndpoints.forEach(endpoint => {
      report.push(`  ${endpoint.endpoint}: ${endpoint.success ? '✅' : '❌'} ${endpoint.message}`)
    })
    report.push('')
    
    report.push('🔌 WebSocket端点检查:')
    results.webSocketEndpoints.forEach(endpoint => {
      report.push(`  ${endpoint.endpoint}: ${endpoint.success ? '✅' : '❌'} ${endpoint.message}`)
    })
    report.push('')
    
    // 建议
    report.push('💡 建议:')
    if (results.summary.failed === results.summary.totalTests) {
      report.push('   - 后端服务可能未启动')
      report.push('   - 检查端口8891是否被占用')
      report.push('   - 确认后端服务配置正确')
    } else if (results.summary.passed > 0) {
      report.push('   - 部分服务可用，检查WebSocket配置')
      report.push('   - 确认WebSocket端点路径')
    }
    
    return report.join('\n')
  }
}

// 创建全局实例
export const backendChecker = new BackendChecker()
